package objects 
{
	/**
	 * ...
	 * @author Tuan
	 */
	import com.greensock.core.PropTween;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import starling.core.Starling;
	import starling.display.Image;
	import starling.display.Sprite;
	import starling.events.Event;
	import starling.display.MovieClip;
	import objects.HealthBar.HealthBar;
	public class Enemy extends MyObject 
	{
		//layer
		public var m_Sprite : Sprite; 
		
		//node of path
		public var currentNode : int; 
		
		//use for path movement
		public var path : Path;
		public var nodes : Array  ;
		
		//velocity
		public var m_desiredV : Point ;
		public var m_steeringV : Point;
		
		
		//force
		public var max_force : Number;
		public var mass: Number;
		
        //animation
		public var m_moveMovie : MovieClip;
		public var m_standMovie : MovieClip;
		public var m_attackMovie : MovieClip;
		public var m_collisionAttack : Boolean;
		public var m_timeStand : Number;
		public var m_scale : Number;
		

		public function Enemy(sprite: Sprite, _pos : Point, _path : Path, _id :int) 
		{
			m_id = _id;
			m_Sprite = sprite;
			
			//path 
			path = _path;
            nodes = path.getNodes();			
			m_pos = _pos;

			this.addEventListener(Event.ADDED_TO_STAGE, init);
			m_Sprite.addChild(this);
		}
		private function init(event:Event):void
		{	
            this.removeEventListener(Event.ADDED_TO_STAGE, init);
			m_newAnimationState = Global.ENEMY_E_MOVE;
			m_animationState = Global.ENEMY_E_MOVE;
			m_movieVector = new Vector.<MovieClip>();
	       
			//velocity, mass, force, current node
			m_desiredV = new Point(1, 1);
			m_velocity = new Point( -1, -1);
			m_steeringV = new Point(0, 0);
			m_maxVelocity = 1.0;
			max_force = m_maxVelocity * 3;
			mass = 0.05;
			currentNode = 0;
			
			//coint
			m_coinEnemy = 3;
			//target pos
			m_coolDown = 0;
			m_collisionAttack = false;
			m_choosedEnemy = null;
			m_targetPos =  nodes[currentNode];
			
			//hp && damage && armor && percent damage
			m_fullHp = 24;
			m_hp = 24;
			m_damage = 2;
		    m_armor = Global.ARMOR_NONE;
			m_percentDamage = 1;
			m_minDamage = 1;
			m_maxDamage = 4;
			
			m_EnemyDestination = false;
			//number solider attaking this enemy
			m_countAttack = 0;
			
			//time stand
			m_timeStand = 0;
			
			//Animation
			m_scale = 0.55;
			m_moveMovie = new MovieClip(Assets.fixgetSpriteSheet().getTextures("emove_"), 6);
			m_moveMovie.pivotX =  m_moveMovie.width / 2;
			m_moveMovie.pivotY =  m_moveMovie.height / 2;
			
			m_moveMovie.scaleX = m_scale;
			m_moveMovie.scaleY = m_scale;
			Starling.juggler.add(m_moveMovie);
			this.addChild (m_moveMovie);
			

					
			m_standMovie = new MovieClip(Assets.fixgetSpriteSheet().getTextures("estand_"), 8);
			m_standMovie.pivotX =  m_standMovie.width / 2;
			m_standMovie.pivotY =  m_standMovie.height / 2;			
			m_standMovie.scaleX = m_scale;
			m_standMovie.scaleY = m_scale;
		
			
			m_attackMovie = new MovieClip(Assets.fixgetSpriteSheet().getTextures("eattack_"), 5);
			m_attackMovie.pivotX =  m_attackMovie.width / 2;
			m_attackMovie.pivotY =  m_attackMovie.height / 2;			
			m_attackMovie.scaleX = m_scale;
			m_attackMovie.scaleY = m_scale;
			
			m_movieVector[Global.ENEMY_E_MOVE] = m_moveMovie;
			m_movieVector[Global.ENEMY_E_STAND] = m_standMovie;
			m_movieVector[Global.ENEMY_E_ATTACKED] = m_attackMovie;
			
			m_movieVector[m_animationState].x = m_pos.x;
			m_movieVector[m_animationState].y = m_pos.y;
			
			//health bar
			m_healthBarRed = new HealthBar(Assets.getSpriteSheet().getTexture("redheathbar") );
			this.addChild (m_healthBarRed);
			m_healthBarRed.x = m_pos.x - m_movieVector[m_animationState].width/2 + 10;
			m_healthBarRed.y = m_pos.y - m_movieVector[m_animationState].height + 5;
			m_healthBarRed.scaleX = m_movieVector[m_animationState].width / m_healthBarRed.mImage.width ;
			m_healthBarRed.scaleY = 0.3;
			m_healthBarRed.ratioH = 1;
			
			m_healthBar = new HealthBar(Assets.getSpriteSheet().getTexture("heathbar") );
			this.addChild (m_healthBar);
			
			m_healthBar.x = m_pos.x - m_movieVector[m_animationState].width/2 + 10;
			m_healthBar.y = m_pos.y - m_movieVector[m_animationState].height + 5;
			m_healthBar.scaleX = m_movieVector[m_animationState].width / m_healthBar.mImage.width ;
			m_healthBar.scaleY = 0.3;
			m_healthBar.ratioH = 1;
			
			

		}
		public function updateHealthBar () : void
		{
			if ( m_movieVector[m_animationState].scaleX > 0)
			{
			  m_healthBar.x = m_pos.x - m_movieVector[m_animationState].width/2 + 5;
			  m_healthBar.y = m_pos.y -  m_movieVector[m_animationState].height + 12;
			
			  m_healthBarRed.x =  m_healthBar.x; 
			  m_healthBarRed.y =  m_healthBar.y;
			}
			else {
			  m_healthBar.x = m_pos.x - m_movieVector[m_animationState].width/2  ; 
			  m_healthBar.y = m_pos.y -  m_movieVector[m_animationState].height + 12;
			
			  m_healthBarRed.x = m_healthBar.x ; 
			  m_healthBarRed.y = m_healthBar.y;
			}
			m_healthBar.ratioH = m_hp / m_fullHp;
		}
		override public function update(dt:Number):void
		{
			updateHealthBar();
			if(m_newAnimationState != m_animationState) // thay animation
			{

				removeChild(m_movieVector[m_animationState]);
				Starling.juggler.remove(m_movieVector[m_animationState]);
 				
				m_animationState = m_newAnimationState;
				addChild(m_movieVector[m_animationState]);
				Starling.juggler.add(m_movieVector[m_animationState]);		
			}
		
			if (m_countAttack <= 0) // khong con ai danh' thi set run
			{
				  m_newAnimationState = Global.ENEMY_E_MOVE; 
			}
			if( m_choosedEnemy!=null && m_choosedEnemy.m_hp <=0 ) // target die
	        {
			   m_countAttack -= 1;
		       m_choosedEnemy = null;
			 
	        }
			
			
			if (m_animationState == Global.ENEMY_E_ATTACKED)
			{
			   if (m_pos.x < m_targetPos.x )
			   {
				 m_movieVector[m_animationState].scaleX = -m_scale;
			   }
			   else if ( m_pos.x >= m_targetPos.x )
			   {
				  m_movieVector[m_animationState].scaleX = m_scale;
			   }
			}
			if (m_animationState == Global.ENEMY_E_STAND)
			{
			   m_timeStand += dt ;
			   
			   if (m_timeStand > 2.5)
			   {
					    m_choosedEnemy = null;
					    m_countAttack = 0;
					    m_newAnimationState = Global.ENEMY_E_MOVE; 
						m_timeStand = 0;
			   }
			   
			   
			   m_velocity = new Point(0, 0);
				
			   if (m_pos.x < m_targetPos.x )
			   {
				 m_movieVector[m_animationState].scaleX = -m_scale;
			   }
			   else if ( m_pos.x >= m_targetPos.x )
			   {
				  m_movieVector[m_animationState].scaleX = m_scale;
			   }
			}
			
			if ( m_animationState == Global.ENEMY_E_MOVE)
			{
			  m_timeStand = 0;	
			  m_steeringV = this.pathFollowing();
			  m_steeringV = this.truncate(m_steeringV, max_force);
			  m_steeringV = ccpMult (m_steeringV, mass);
			 
			  m_velocity = m_velocity.add(m_steeringV);
			  m_velocity = this.truncate ( m_velocity, m_maxVelocity); 
			
			
			  m_pos.x =  m_pos.x + m_velocity.x;
			  m_pos.y  = m_pos.y + m_velocity.y;
			 
			}	
			m_movieVector[m_animationState].x = m_pos.x;
			m_movieVector[m_animationState].y = m_pos.y;
			

			if (m_collisionAttack == true)
			{
				m_coolDown += dt;
				if (m_coolDown >=0.4 ) 
				{
					m_coolDown = 0;
					m_collisionAttack = false;
				}

			  m_movieVector[m_animationState].x = m_pos.x;
			  m_movieVector[m_animationState].y = m_pos.y;

			}
			

			if (m_animationState == Global.ENEMY_E_ATTACKED) 
			{
				
				if (m_choosedEnemy!=null && m_movieVector[m_animationState].currentFrame >= 1&&  m_movieVector[m_animationState].currentFrame <=2 && m_collisionAttack ==false )
				{
					if ( m_movieVector[m_animationState].bounds.intersects ( m_choosedEnemy.getRect()) == false)
					{
		//				 trace ("enemy danh truot solider");
					}
					if (m_movieVector[m_animationState].bounds.intersects ( m_choosedEnemy.getRect() ))
					{
					  m_collisionAttack = true;
					  
					  
					  if (m_choosedEnemy.m_armor == Global.ARMOR_NONE)
					   {
					       m_choosedEnemy.m_hp -= this.m_damage ;
					   }
					     else if (m_choosedEnemy.m_armor == Global.ARMOR_LOW)
				         {
						   m_damage = randomRange(m_minDamage, m_maxDamage);	 
					       m_percentDamage = randomRange (1, 20);
					       this.m_damage = this.m_damage - this.m_damage * m_percentDamage / 100;
					       m_choosedEnemy.m_hp -= this.m_damage ;
				         }
						 else if (m_choosedEnemy.m_armor == Global.ARMOR_MEDIUM)
				         {
						   m_damage = randomRange(m_minDamage, m_maxDamage); 
					       m_percentDamage = randomRange (21, 50);
					       this.m_damage = this.m_damage - this.m_damage * m_percentDamage / 100;
					       m_choosedEnemy.m_hp -= this.m_damage ;
				         }
						 else if (m_choosedEnemy.m_armor == Global.ARMOR_HIGH)
				         {
						   m_damage = randomRange(m_minDamage, m_maxDamage); 
					       m_percentDamage = randomRange (51, 74);
					       this.m_damage = this.m_damage - this.m_damage * m_percentDamage / 100;
					       m_choosedEnemy.m_hp -= this.m_damage ;
				         }
						 else if (m_choosedEnemy.m_armor == Global.ARMOR_HIGH)
				         {
						   m_damage = randomRange(m_minDamage, m_maxDamage); 
					       m_percentDamage = randomRange (75, 95);
					       this.m_damage = this.m_damage - this.m_damage * m_percentDamage / 100;
					       m_choosedEnemy.m_hp -= this.m_damage ;
				         }
					}
				}
			}

	
		}
		private function pathFollowing() :Point
		{
			if (path != null)
			{
				
				m_targetPos = nodes[currentNode]; //current node : node hien. tai. dang huong' toi'
				if (this.Distance ( m_pos, m_targetPos) <= path.getRadiusPath())
				{
					currentNode += 1;
					if (currentNode >= nodes.length)
					{
						//currentNode = nodes.length -1;
						this.m_hp = 0;
						this.m_EnemyDestination = true;
					}
				}
			}
			if (m_pos.x < m_targetPos.x  ) // global move
			{
				m_movieVector[m_animationState].scaleX = -m_scale;
			}
			else if ( m_pos.x >= m_targetPos.x )
			{
				m_movieVector[m_animationState].scaleX = m_scale;
			}
		
			return this.seek(m_targetPos);
		}
		
		
		private function seek (target : Point) : Point
		{
			m_desiredV =  m_targetPos.subtract(m_pos);
			m_desiredV.normalize(1) ;
			m_desiredV = ccpMult ( m_desiredV, m_maxVelocity);
			
			return m_desiredV.subtract(m_velocity);
		}
		private function truncate ( vector :Point, max :Number): Point
		{
			
			var i : Number =  vector.length / max;
			i = i < 1.0 ? 1.0 : 1 / i;
			return ccpMult (vector, i);
		}
		private function Distance ( a: Point, b :Point) : Number
		{
			return Math.sqrt (  (a.x - b.x) * ( a.x - b.x) + (a.y - b.y) * (a.y - b.y) );
		}
	
		override public function Collision(_enemy:MyObject, dt:Number):void
		{
		}
		override public function getRect():Rectangle
		{
		    return m_movieVector [m_animationState].bounds ;	
		}

		override public function release() : void {
		   removeChild(m_movieVector[m_animationState]);
		   Starling.juggler.remove(m_movieVector[m_animationState]);
		   m_movieVector = null;
		   removeChildren();
		}
	}
}